using Microsoft.Extensions.Configuration;
using UniversalAdminSystem.Application.Common.Interfaces;
using System.Text;
using RabbitMQ.Client;

namespace UniversalAdminSystem.Infrastructure.RabbitMQ;

public class RabbitMqEventBus : IEventBus, IDisposable
{
  private readonly IConnection _conn;

  public RabbitMqEventBus(IConnection conn, IConfiguration _)
  {
    _conn = conn;
  }

  public Task PublishAsync(string exchange, string routingKey, string payload, string? messageId = null, CancellationToken ct = default)
  {
    // 每次发布各自创建 channel，线程安全 & 生命周期正确
    using var ch = _conn.CreateModel();
    ch.ConfirmSelect();
    var props = ch.CreateBasicProperties();
    props.Persistent = true;
    props.MessageId = messageId;
    props.ContentType = "application/json";
    var body = Encoding.UTF8.GetBytes(payload);
    ch.BasicPublish(exchange, routingKey, mandatory: false, basicProperties: props, body: body);

    // publisher confirm，确保消息真正进 broker
    ch.WaitForConfirmsOrDie(TimeSpan.FromSeconds(5));
    return Task.CompletedTask;
  }

  public void Dispose() { }
}